package com.yuma.strategy;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class AlgorithmUtil implements ApplicationContextAware {

    Map<AlgorithmType, Algorithm> map = new HashMap<>();

    /*public AlgorithmUtil(){
        map.put(AlgorithmType.AES, new AES());
        map.put(AlgorithmType.DES, new DES());
        map.put(AlgorithmType.MD5, new Md5());
        map.put(AlgorithmType.SHA, new SHA());
    }*/

    public String encrypt(AlgorithmType key, String string){
        return map.get(key).encrypt(string);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //  获取所有带MyAlgorithm注解的bean
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(MyAlgorithm.class);
        beans.values().forEach(bean -> {
            map.put(bean.getClass().getAnnotation(MyAlgorithm.class).value(), (Algorithm) bean);
        });
    }
}
